<?php
declare (strict_types = 0);
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\Cache;
use app\controller\Token;
use app\model\DeptModel;
use app\model\UserModel;
use app\Common;


class Dept{
    //常用数据表内容 及常用字典

    var $dept=[];
    var $sex=[1=>'男',2=>'女'];

    var $status=array(1=>'正常',2=>'关闭',3=>'待审核',4=>'审核驳回');
    var $back = "<script>setTimeout(function(){history.back();},3000)</script>";

    public function __construct(){
        $um=new UserModel();
        $this->users = $um->getAll();

        $list = Db::table("dept")->select()->toArray();
        foreach($list as $k=>$v){
            $this->dept[$v['id']]=$v;
        }

        $um=new DeptModel();
        $this->dept = $um->getAll(1);


    }

    //部门
    public function index(){
        $uid = Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');

        $user =Db::table('user')->find($uid);
        $dept = new DeptModel();
        $list=$dept->deptTree($user['dept_id']); 

        foreach($list as &$kv){
            $kv['fid_name'] = $kv['fid'] ? $this->dept[$kv['fid']]['name']:'';            
            $kv['status_name'] = $this->status[$kv['status']];
            $kv['creater_name'] = $this->users[$kv['creater']]['name'];
            $kv['user_id_name'] = $kv['user_id']?$this->users[$kv['user_id']]['name']:'';
            //$kv['ad_img']=explode(",",$kv['ad_img']);
        }

        View::assign(['data'=>$list]);

        return View::fetch();
    }

    //入驻资料
    public function shop_info(){
        $all=Request::param();
        //保存资料
        if(!empty($all['post'])){
            $arr= [
              "name" => $all['name'],
              "boss_name" => $all['boss_name'],
              "mobile" => $all['mobile'],
              'city'=>$all['city'],
              "address" => $all['address_2'],
              "shop_img" => implode(",",$all['shop_img']),
              "id_img" => implode(",",$all['id_img']),
              "bus_license_img" => implode(",",$all['bus_license_img']),
              'status'=>3,
              'create_time'=>date('Y-m-d H:i:s'),

            ];

            $res = Db::table('dept_info')->insertGetId($arr);
            return json(['code'=>1,'msg'=>'提交成功，请耐心等待审核入驻！']);
        }

        if(!empty($all['token'])){
            //我的入驻资料
            $token = new Token();
            $arr = $token->check_token($all['token']); 
            if($arr['code']<1){
                return json($arr);
            }

            $token_info=$arr;
            if($token_info['type']!=3){
                return json(['code'=>0,'msg'=>'你不是加盟商!']);
            }
            
            $customer=$token_info['customer'];
            $dept=Db::table('dept')->where('id',$customer['dept_id'])->value('id');            
        }else if(!empty($all['dept_id'])){
            $dept=$all['dept_id'];
        }else{
            return json(['code'=>0,'msg'=>'缺少必要参数！']);
        }

        //获取资料
        $data=Db::table('dept_info')->where('dept_id',$dept)->find(); 
        if(!$data) return json(['code'=>0,'msg'=>'没有商家入驻资料！']);

        $data['status_name']=$this->status[$data['status']];
        $data['ad_img']=explode(",",$data['ad_img']);

        return json(['code'=>1,'data'=>$data]);


    }


    //店铺列表
    public function shop_list(){
        $all=Request::param();

        $list =Db::table('dept_info')->where('status','1'); 

        //热门
        if(!empty($all['hot'])){
            $list =$list->limit(12)->order('star','desc')->column('id,dept_id,name,shop_img');
            return json($list);
        }


        if(!empty($all['dept_id'])){
            $list =$list->where('dept_id',$all['dept_id']);
        }

        if(!empty($all['city'])){
            $list =$list->where('city','like','%'.$all['city'].'%');
        }

        if(!empty($all['name'])){
            $list =$list->where('name','like','%'.$all['name'].'%');
        }

        $list = $list->select()->toArray();

        foreach($list as &$dept){
            $dept['ad_img'] = explode(",",$dept['ad_img']);
            $dept['title'] = Db::table('table')->where('id',$dept['dept_id'])->value('title');
        }

        return json($list);
    }
    
    //驾校入住审核，后台操作
    public function check(){
        $uid = Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');

        $all = Request::param();
        if(!empty($all['id'])){
            if($all['status']==4){ //驳回

                Db::table('dept_info')->update($all);
                return json(['code'=>1,'msg'=>'已驳回！']);
            }

            if($all['status']==1){
                $name=Db::table('dept_info')->where('id',$all['id'])->value('name');
                $exist=Db::table('dept')->where('name',$name)->find();
                if($exist) return json(['code'=>0,'msg'=>'驾校【'.$exist['name'].'】已经存在！']);

                $all['check_time']=date('Y-m-d H:i:s');
                $all['checker'] = $uid;                

                $data = Db::table('dept_info')->find($all['id']);
                $dept_arr=array(
                    'name'=>$data['name'],
                    'title'=>$data['name'],
                    'type'=>2,
                    'status'=>1,
                    'fid'=>1,
                    'create_time'=>date('Y-m-d H:i:s'),
                    'creater'=>$data['checker']
                );
                $new_id =Db::table('dept')->insertGetId($dept_arr);
                $all['dept_id'] =$new_id;
                $res =Db::table('dept_info')->update($all);

                //审核通过后，检查是否有管理用户存在：提交资料的手机号码
                $user = Db::table('user')->where('mobile',$data['mobile'])->find();
                if($user){
                    //原来建过用户就直接绑定成新机构负责人
                    Db::table('dept')->update(['id'=>$new_id,'user_id'=>$user['id']]);
                }else{
                    //建立新的用户，并绑定成负责人
                    $ct = date('Y-m-d H:i:s');
                    $pwd = md5('12345think');
                    $user_arr=array(
                        'dept_id'=>$new_id,
                        'name'=>$data['boss_name'],
                        'native_address'=>$data['city'],
                        'address' =>$data['address'],
                        'mobile'=>$data['mobile'],
                        'status'=>1,
                        'uid'=>Common::randomString(10),
                        'group_id'=>7,
                        'creater'=>2,
                        'create_time'=>$ct,
                        'password'=>md5('12345think'),
                        'verify_code' =>md5($pwd.$ct)
                    );
                    $nu_id=Db::table('user')->insertGetId($user_arr);
                    $res = Db::table('dept')->update(['id'=>$new_id,'user_id'=>$nu_id]);
                }


                if($res){
                    return json(['code'=>1,'msg'=>'已通过！']);
                }else{
                    return json(['code'=>0,'msg'=>'Fail!']);
                }
            }
        }


        $name=!empty($all['name'])?$all['name']:'';
        $status=!empty($all['status'])?$all['status']:'1,3,4';

        $list =Db::table('dept_info')->where('status','in',$status);
        $user = $this->users[$uid];
        if($user['group_id']!=1){
            $list->where('dept_id',$user['dept_id']);
        }            

        $list = $list->order('create_time')->paginate(20)->toArray();

        foreach($list['data'] as &$dept){
            $dept['status_name']=$this->status[$dept['status']];
            $dept['id_img'] = explode(",",$dept['id_img']);
            $dept['ad_img'] = explode(",",$dept['ad_img']);
        }
        //halt($list);

        if($status=='1,3,4') $status='';

        View::assign(['list'=>$list,'name'=>$name,'status'=>$status]);
        return View::fetch('school_check');
    }


    //编辑方法
    public function edit(){
        $uid = Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');

        $all = Request::param();
        $id=$all['id'];
        $view='edit'; //模板

        if(empty($id)) return '错误!'.$this->back;
        $dept = new DeptModel();

        //传入内容,保存数据并跳转
        if($id>0 && !empty($all['name'])){
            $all['update_time'] = date('Y-m-d H:i:s');
            $all['updater'] = $uid;
            if($all['id']==1) $all['fid']=0;

            $row = $dept::where('name',$all['name'])->where('id','<>',$all['id'])->find();
            if(!empty($row)) return '组织已存在,['. $all['name']."]".$this->back;            

            //halt($all,$_FILES);

            $arr_dept=array(
                'id'=>$all['id'],
                'name'=>$all['name'],
                'title'=>$all['title'],
                'user_id'=>$all['user_id'],
                'tel'=>$all['mobile'],
                'address'=>$all['address'],
                'update_time'=>date('Y-m-d H:i:s'),
                'updater'=>$uid,
                'status'=>$all['status']

            );
            Db::table('dept')->save($arr_dept);

            //保存资料
            $ad_img=[];
            if($_FILES['file1']['size']>0){
                foreach($_FILES as $file){
                    if($file['size']>0){
                        $files =Common::upload($file);
                        if($files['code']){
                            $ad_img[]=$files['msg'];
                        }
                    }
                }
                $ad_img = implode(",",$ad_img); 
            }

            //门头
            if($_FILES['shop_img']['size']>0){
                $file_shop =Common::upload($_FILES['shop_img']);
                if($file_shop['code']){
                    $shop_img=$file_shop['msg'];
                }
            }
            //营业执照
            if($_FILES['bus_license_img']['size']>0){
                $file_bl =Common::upload($_FILES['bus_license_img']);
                if($file_bl['code']){
                    $bus_license_img=$file_bl['msg'];
                }
            }
            //身份证
            if($_FILES['id_img']['size']>0){
                $file_bl =Common::upload($_FILES['id_img']);
                if($file_bl['code']){
                    $id_img=$file_bl['msg'];
                }
            }

            $dept_info=array(
                'id'=>Db::table('dept_info')->where('dept_id',$all['id'])->value('id'),
                'name'=>$all['name'],
                'mobile'=>$all['mobile'],
                'city'=>$all['city'],
                'address'=>$all['address'],
                'lat'=>$all['lat'],
                'lng'=>$all['lng']
            );

            if($ad_img!='') {               $dept_info['ad_img'] =$ad_img;}
            if(isset($id_img)) {            $dept_info['id_img'] =$id_img;}
            if(isset($shop_img)){           $dept_info['shop_img'] = $shop_img;}
            if(isset($bus_license_img)){    $dept_info['bus_license_img'] = $bus_license_img;}
            //halt($dept_info,$ad_img);

            if(!empty($all['user_id'])) $dept_info['boss_name']= $this->users[$all['user_id']]['name'];

            Db::table('dept_info')->save($dept_info);

            return header('location:/index.php/dept/check');
        }

        //不传内容只有id,查出本条数据 并进入编辑

        $row = Db::table('dept')->find($all['id']);
        $row['user_id_name'] =$row['user_id']?$this->users[$row['user_id']]['name']:'';

        //驾校编辑
        if($row['type']==2){
            $view = 'school_edit';
            $row['info'] = Db::table('dept_info')->where('dept_id',$all['id'])->find();

            $row['id_img']=[];
            if(!empty($row['info']['id_img'])){
                $ids = explode(",",$row['info']['id_img']);
                $row['id_img'] =$ids;
            }
            $row['ad_img']=[];
            if(!empty($row['info']['ad_img'])){
                $ads = explode(",",$row['info']['ad_img']);
                $row['ad_img'] = $ads;
            }
        }

        View::assign([
            'dept'=>$this->dept,
            'status'=>$this->status,
            'data'=>$row]);

        return View::fetch($view);
    }

    //部门新增
    public function dept_add(){
        $uid = Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');

        $all = Request::param();// print_r($all);exit;
        if($all){
            if(!empty($all['id'])) return '错误!'.$this->back;     
            if(!$all['name']) return '无效的组织名称!'.$this->back;

            $dept = new DeptModel();
            $row = $dept::where('name',$all['name'])->find();
            if(!empty($row)) return '组织已存在,['. $all['name']."]".$this->back;

            $all['creater']  = Session::get('logonid');
            $all['create_time']  = date("Y-m-d H:i:s",time());

            unset($all['file']);

            $new_id =$dept->insertGetId($all);
            if($new_id && $all['type']==2){
                $arr=array(
                    'dept_id'=>$new_id,
                    'name'=>$all['name'],
                    'mobile'=>$all['mobile'],
                    'address'=>$all['address'],
                    'status'=>$all['status'],
                    'create_time'=>$all['create_time']

                );
                $res = Db::table('dept_info')->insert($arr);
            }

            header("location:/index.php/dept");
        }
        View::assign([
            'dept'=>$this->dept,
            'status'=>$this->status,
        ]);
        return View::fetch('dept_add');
    }

    public function resetpwd($id){
        $uid = Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');
                
        if(empty($id)) return 'error action!';
        $user = new UserModel();

        $res = $user->update(['id'=>$id,'password'=>md5('12345')]);
        return("Password reseted to '12345'!<br /><a href='/index.php/user'>back</a>");
        //header("location:/index.php/user");
    }


    public function getMyDepts($uid=''){
        $uid = Session::get('logonid');
        if(!$uid) return header('location:/index.php/login/target/admin');

        $user = Db::table('user')->find($uid);
        $depts=$this->getChildren($user['dept_id']);
        return $depts;

    }

    //取得子部门
    private function getChildren($id,$arr=[]){
        $arr[]=$this->dept[$id];
        foreach($this->dept as $d){
            if($d['fid']==$id){
                $arr[] = $d;
                $this->getChildren($d['id'],$arr);
            }
        }
        return $arr;
    }

}
